

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="深海火锅店">
  <meta name="keywords" content="">
  
    <meta name="description" content="窗口:窗口的概念非常重要，它可以理解为记录集合。窗口函数:在满足某些条件的记录集合上执行的特殊函数，对于每条记录都要在此窗口内执行函数。有的函数随着记录的不同窗口大小都是固定的，称为静态窗口;有的函数则相反，不同的记录对应着不同的窗口，称为滑动窗口 窗口函数和普通聚合函数的区别聚合函数是将多条记录聚合为一条;窗口函数是每条记录都会执行，有几条记录执行完还是几条，不会改变记录的数量聚合函数也可以用于">
<meta property="og:type" content="article">
<meta property="og:title" content="DB17_分析函数1-窗口函数">
<meta property="og:url" content="http://example.com/2022/12/28/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB16&DB17/DB17_%E5%88%86%E6%9E%90%E5%87%BD%E6%95%B01-%E7%AA%97%E5%8F%A3%E5%87%BD%E6%95%B0/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="窗口:窗口的概念非常重要，它可以理解为记录集合。窗口函数:在满足某些条件的记录集合上执行的特殊函数，对于每条记录都要在此窗口内执行函数。有的函数随着记录的不同窗口大小都是固定的，称为静态窗口;有的函数则相反，不同的记录对应着不同的窗口，称为滑动窗口 窗口函数和普通聚合函数的区别聚合函数是将多条记录聚合为一条;窗口函数是每条记录都会执行，有几条记录执行完还是几条，不会改变记录的数量聚合函数也可以用于">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-12-28T02:00:00.000Z">
<meta property="article:modified_time" content="2022-12-31T09:25:14.000Z">
<meta property="article:author" content="深海火锅店">
<meta property="article:tag" content="大数据">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>DB17_分析函数1-窗口函数 - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/background.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="DB17_分析函数1-窗口函数"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-12-28 10:00" pubdate>
          2022年12月28日 上午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          3.6k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          30 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">DB17_分析函数1-窗口函数</h1>
            
            
              <div class="markdown-body">
                
                <p>窗口:窗口的概念非常重要，它可以理解为记录集合。<br>窗口函数:在满足某些条件的记录集合上执行的特殊函数，对于每条记录都要在此窗口内执行函数。有的函数随着记录的不同窗口大小都是固定的，称为静态窗口;有的函数则相反，不同的记录对应着不同的窗口，称为滑动窗口</p>
<p>窗口函数和普通聚合函数的区别<br>聚合函数是将多条记录聚合为一条;窗口函数是每条记录都会执行，有几条记录执行完还是几条，不会改变记录的数量<br>聚合函数也可以用于窗口函数，相对MySQL，PostgreSQL和Oracle提供更多聚合函数对于窗口的支持</p>
<p>窗口函数的基本用法<br>函数名OVER子句<br>OVER关键字用来指定函数执行的窗口范围，若后面括亏中什么都个与，则忌添自凶H基于所有行进行计算;如果不为空，则支持以下4中语法来设置窗口。<br>WINDOW NAME:给窗口指定一个别名。如果SQL中涉及的窗口较多，采用别名可以看起来更清晰易读;<br>PARTITION BY子句:窗口按照哪些字段进行分组，窗口函数在不同的分组上分别执行;<br>ORDER BY子句:按照哪些字段进行排序，窗口函数将按照排序后的记录顺序进行编号;<br>FRAME子句:FRAME是当前分区的一个子集，子句用来定义子集的规则，通常用来作为滑动窗口使用。</p>
<h3 id="窗口函数的使用场景"><a href="#窗口函数的使用场景" class="headerlink" title="窗口函数的使用场景"></a>窗口函数的使用场景</h3><p>在日常工作中经常会遇到类似这样的需求<br>医院看病，怎样知道上次就医距现在的时间?<br>产品销售的环比如何计算?<br>怎么样得到各部门工资排名前N名员工列表?<br>查找各部门每人工资占部门总工资的百分比?<br>对于这样的需求，使用传统的SQL实现起来比较困难。这类需求都有一个共同的特点<br>需要在单表中满足某些条件的记录集内部<br>做一些函数操作，不是简单的表连接，也不是简单的聚合可以实现的，通常会让写SQL的同学焦头烂额、绞尽脑汁，费了大半天时间写出来一堆长长的晦涩难懂的自连接SQL，且性能低下，难以维护。<br>要解决此类问题，最方便的就是使用窗口函数。</p>
<h3 id="序号函数-row-number"><a href="#序号函数-row-number" class="headerlink" title="序号函数-row_number()"></a>序号函数-row_number()</h3><p>用途:显示分区中的当前行号<br>应用场景:查询每个学生的分数最高的前3门课程<br>语法<br>ROW_NUMBER() OVER(PARTITION BY 分区字段名 ORDER BY 排序字段名)<br>例：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> student_id, score_rnk, score<br><span class="hljs-keyword">FROM</span> (<span class="hljs-keyword">SELECT</span> student_id,<br>             <span class="hljs-built_in">ROW_NUMBER</span>() <span class="hljs-keyword">OVER</span> (<span class="hljs-keyword">partition</span> <span class="hljs-keyword">by</span> student_id<br>                 <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> score <span class="hljs-keyword">DESC</span> ) <span class="hljs-keyword">AS</span> score_rnk,<br>             course_id,<br>             score<br>      <span class="hljs-keyword">FROM</span> sales.t_scores) <span class="hljs-keyword">AS</span> t1<br><span class="hljs-keyword">WHERE</span> t1.score_rnk <span class="hljs-operator">&lt;=</span> <span class="hljs-number">3</span>;<br></code></pre></td></tr></table></figure>

<h3 id="序号函数-rank"><a href="#序号函数-rank" class="headerlink" title="序号函数-rank()"></a>序号函数-rank()</h3><p>对于号码220101的同学，有两门课程的成绩均为98，序号随机排了2和3。但很多情况下二者应该是并列第2，这时候，ROW_NUMBER()就不能满足需求，需要RANK()和DENSE_RANK()出场，它们和ROW_NUMBER()非常类似，只是在出现重复值时处理逻辑有所不同。<br>语法：<br>RANKO OVER(PARTITION BY分区字段名ORDER BY 排序字段名)<br>例：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> student_id, score_rnk, score<br><span class="hljs-keyword">FROM</span> (<span class="hljs-keyword">SELECT</span> student_id,<br>             <span class="hljs-built_in">RANK</span>() <span class="hljs-keyword">OVER</span> (<span class="hljs-keyword">partition</span> <span class="hljs-keyword">by</span> student_id<br>                 <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> score <span class="hljs-keyword">DESC</span> ) <span class="hljs-keyword">AS</span> score_rnk,<br>             course_id,<br>             score<br>      <span class="hljs-keyword">FROM</span> sales.t_scores) <span class="hljs-keyword">AS</span> t1<br><span class="hljs-keyword">WHERE</span> t1.score_rnk <span class="hljs-operator">&lt;=</span> <span class="hljs-number">3</span>;<br></code></pre></td></tr></table></figure>

<p>RANK():并列排序，跳过重复序号,1,2,2,4<br>比如220101有两个98、所以并列第2，该学生的下一条记录的序号为4，而不是3</p>
<h3 id="序号函数-dense-rank"><a href="#序号函数-dense-rank" class="headerlink" title="序号函数-dense_rank()"></a>序号函数-dense_rank()</h3><p>语法：<br>DENSE_RANK( OVER (PARTITION BY 分区字段名ORDER BY 排序字段名)<br>例：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> student_id, score_rnk, score<br><span class="hljs-keyword">FROM</span> (<span class="hljs-keyword">SELECT</span> student_id,<br>             <span class="hljs-built_in">DENSE_RANK</span>() <span class="hljs-keyword">OVER</span> (<br>                 <span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> student_id<br>                 <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> score <span class="hljs-keyword">DESC</span> ) <span class="hljs-keyword">AS</span> score_rnk,<br>             course_id,<br>             score<br>      <span class="hljs-keyword">FROM</span> sales.t_scores) <span class="hljs-keyword">AS</span> t1<br><span class="hljs-keyword">WHERE</span> t1.score_rnk <span class="hljs-operator">&lt;=</span> <span class="hljs-number">3</span>;<br></code></pre></td></tr></table></figure>

<p>DENSE_RANK():并列排序，不跳过重复序号<br>比如220101有两个98，所以并列第2，该学生的下―条记录的序号顺序跟进为3</p>
<h3 id="分布函数-cume-dist"><a href="#分布函数-cume-dist" class="headerlink" title="分布函数-cume_dist()"></a>分布函数-cume_dist()</h3><p>用途:分组内小于等于当前rank值的行数&#x2F;分组内总行数<br>应用场景:查询小于等于当前成绩(score)的比例<br>语法：<br>不指定PARTITION BY则所有数据为一个组，行数为COUNT的结果·指定PARTITION BY则按照设定的字段分组<br>例：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> student_id,<br>       course_id,<br>       score,<br>       <span class="hljs-built_in">CUME_DIST</span>() <span class="hljs-keyword">OVER</span> (<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> score)                        <span class="hljs-keyword">AS</span> cd1,<br>       <span class="hljs-built_in">CUME_DIST</span>() <span class="hljs-keyword">OVER</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> course_id <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> score) <span class="hljs-keyword">AS</span> cd2<br><span class="hljs-keyword">FROM</span> sales.t_scores<br><span class="hljs-keyword">WHERE</span> course_id <span class="hljs-keyword">IN</span> (<span class="hljs-string">&#x27;C001&#x27;</span>, <span class="hljs-string">&#x27;C003&#x27;</span>);<br></code></pre></td></tr></table></figure>

<h3 id="前后函数-lag-expr-n"><a href="#前后函数-lag-expr-n" class="headerlink" title="前后函数-lag(expr,n)"></a>前后函数-lag(expr,n)</h3><p>用途:返回位于当前行的前n行<br>应用场景:查询前1名同学的成绩和当前同学成绩的差值。在数据分析基于月份n&#x3D;1，12可以分别进行环比和同比的计算<br>用法：<br>LAG （PARTITION BY字段名称ORDER BY字段名称)<br>先通过LAG()函数得到前1记录，再将当前记录和前1行记录的计算差值<br>例子</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> student_id,<br>       course_id,<br>       score,<br>       <span class="hljs-built_in">LAG</span>(score, <span class="hljs-number">1</span>) <span class="hljs-keyword">OVER</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> course_id <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> score)  <span class="hljs-keyword">AS</span> prev_score,<br>       score <span class="hljs-operator">-</span><br>       <span class="hljs-built_in">LAG</span>(score, <span class="hljs-number">1</span>) <span class="hljs-keyword">OVER</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> course_id <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> score ) <span class="hljs-keyword">AS</span> diff<br><span class="hljs-keyword">FROM</span> sales.t_scores<br><span class="hljs-keyword">WHERE</span> course_id <span class="hljs-keyword">IN</span> (<span class="hljs-string">&#x27;C001&#x27;</span>, <span class="hljs-string">&#x27;C003&#x27;</span>);<br></code></pre></td></tr></table></figure>


<h3 id="前后函数-lead-expr-n"><a href="#前后函数-lead-expr-n" class="headerlink" title="前后函数-lead(expr,n)"></a>前后函数-lead(expr,n)</h3><p>用法<br>LEAD( PARTITION BY字段名称ORDER BY字段名称)<br>先通过LEAD()函数得到前1记录，再将当前记录和前1行记录的计算差值</p>
<h3 id="头尾函数-first-value-expr-x2F-last-value-expr"><a href="#头尾函数-first-value-expr-x2F-last-value-expr" class="headerlink" title="头尾函数-first_value(expr)&#x2F;last_value(expr)"></a>头尾函数-first_value(expr)&#x2F;last_value(expr)</h3><p>·用途:返回第一个FIRST_VALUE(expr)或最后一个LAST_VALUE(expr)的值<br>·应用场景:截止到当前成绩，按照成绩排序查询第1个和最后1个同学的分数，即第一名和最后一名<br>用法：<br>.FIRST_VALUE&#x2F;LAST_VALUE(字段名）OVER ( PARTITION BY 字段名称 ORDER BY字段名称)<br>例：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> student_id,<br>       course_id,<br>       score,<br>       <span class="hljs-built_in">FIRST_VALUE</span>(score) <span class="hljs-keyword">OVER</span> w <span class="hljs-keyword">AS</span> first_score,<br>       <span class="hljs-built_in">LAST_VALUE</span>(score) <span class="hljs-keyword">OVER</span> w  <span class="hljs-keyword">AS</span> last_score<br><span class="hljs-keyword">FROM</span> sales.t_scores<br><span class="hljs-keyword">WHERE</span> course_id <span class="hljs-keyword">IN</span> (<span class="hljs-string">&#x27;C001&#x27;</span>, <span class="hljs-string">&#x27;C003&#x27;</span>)<br>    <span class="hljs-keyword">WINDOW</span> w <span class="hljs-keyword">AS</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> course_id <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> score <span class="hljs-keyword">DESC</span>);<br></code></pre></td></tr></table></figure>

<p>窗口按照score降序，所以first score对每门课是固定，但是last_score会随着窗口滑动而发生变化</p>
<h3 id="nth-value-expr-n"><a href="#nth-value-expr-n" class="headerlink" title="nth_value(expr,n)"></a>nth_value(expr,n)</h3><p>·用途:返回窗口中第n个expr的值。expr可以是表达式，也可以是列名<br>·应用场景:截止到当前成绩，显示每个同学的成绩中排名第2和第3的课程编码<br>用法：<br>NTH_VALUE(字段名) OVER ( PARTITION BY 字段名称 ORDER BY 字段名称)<br>例：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> student_id,<br>       course_id,<br>       score,<br>       <span class="hljs-built_in">NTH_VALUE</span>(course_id, <span class="hljs-number">2</span>) <span class="hljs-keyword">OVER</span> w <span class="hljs-keyword">AS</span> second_score,<br>       <span class="hljs-built_in">NTH_VALUE</span>(course_id, <span class="hljs-number">3</span>) <span class="hljs-keyword">OVER</span> w <span class="hljs-keyword">AS</span> thrid_score<br><span class="hljs-keyword">FROM</span> sales.t_scores<br><span class="hljs-keyword">WHERE</span> student_id <span class="hljs-keyword">IN</span> (<span class="hljs-string">&#x27;220101&#x27;</span>, <span class="hljs-string">&#x27;220102&#x27;</span>)<br>    <span class="hljs-keyword">WINDOW</span> w <span class="hljs-keyword">AS</span> (<span class="hljs-keyword">PARTITION</span> <span class="hljs-keyword">BY</span> student_id <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> score <span class="hljs-keyword">DESC</span>);<br></code></pre></td></tr></table></figure>
<p>窗口按照score降序，所以first_score对每门课是固定，但是last_score会随着窗口滑动而发生变化</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%A4%A7%E6%95%B0%E6%8D%AE/" class="category-chain-item">大数据</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/">#大数据</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>DB17_分析函数1-窗口函数</div>
      <div>http://example.com/2022/12/28/数据库/MySQL/大数据学习/DB16&amp;DB17/DB17_分析函数1-窗口函数/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>深海火锅店</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年12月28日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/12/29/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB18&amp;DB19/DB18_%E5%88%86%E6%9E%90%E5%87%BD%E6%95%B02-%E7%AA%97%E5%8F%A3%E8%81%9A%E5%90%88%E5%87%BD%E6%95%B0%20copy/" title="DB18_分析函数2-窗口函数">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">DB18_分析函数2-窗口函数</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/12/28/%E6%95%B0%E6%8D%AE%E5%BA%93/MySQL/%E5%A4%A7%E6%95%B0%E6%8D%AE%E5%AD%A6%E4%B9%A0/DB16&amp;DB17/DB16_%E7%BB%84%E5%90%88%E6%9F%A5%E8%AF%A2/" title="DB16_组合查询">
                        <span class="hidden-mobile">DB16_组合查询</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/EmoryHuang/BlogBeautify@1.1/DynamicRibbon.min.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
